package com.fairylove.rpc.transport.utils;

import com.fairylove.rpc.entity.RpcRequest;
import com.fairylove.rpc.enums.PackageType;
import com.fairylove.rpc.serializer.CommonSerializer;

import java.io.IOException;
import java.io.OutputStream;

public class ObjectWriter {

    private static final  int MAGIC_NUMBER = 0xCAFEBABE;

    public static void writeObject(OutputStream outputStream, Object obj, CommonSerializer serializer) throws IOException {

        //写入魔数
        outputStream.write(intToBytes(MAGIC_NUMBER));
        //判断对象是否是rpcRequest对象
        //写入发送对象类别
        if(obj instanceof RpcRequest){
            outputStream.write(intToBytes(PackageType.REQUEST_PACK.getCode()));
        }else{
            outputStream.write(intToBytes(PackageType.RESPONSE_PACK.getCode()));
        }
        //写入序列化类别
        outputStream.write(intToBytes(serializer.getCode()));

        byte[] bytes = serializer.serialize(obj);
        //写入发送字节长度
        outputStream.write(intToBytes(bytes.length));
        outputStream.write(bytes);
        outputStream.flush();

    }

    private static byte[] intToBytes(int value) {
        byte[] src = new byte[4];
        src[0] = (byte) ((value>>24) & 0xFF);
        src[1] = (byte) ((value>>16)& 0xFF);
        src[2] = (byte) ((value>>8)&0xFF);
        src[3] = (byte) (value & 0xFF);
        return src;
    }
}
